package com.cheer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.dao.MallCreditRecordDao;
import com.cheer.entity.MallCreditRecordEntity;
import com.cheer.service.MallCreditRecordService;
import com.cheer.vo.CreditDateVO;
import com.cheer.vo.CreditRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service("mallCreditRecordService")
public class MallCreditRecordServiceImpl extends ServiceImpl<MallCreditRecordDao, MallCreditRecordEntity> implements MallCreditRecordService {

    @Autowired
    private MallCreditRecordDao mallCreditRecordDao;

    @Override
    public List<CreditDateVO> listCredit(Integer pageNum, Integer pageSize, Integer userId) {
        int start = (pageNum - 1) * pageSize;
        int offset = pageSize;
        List<MallCreditRecordEntity> creditRecordList = mallCreditRecordDao.selectListByUserIdLimit(start, offset, userId);

        Map<String, List<CreditRecordVO>> map = new LinkedHashMap<>();
        for (MallCreditRecordEntity creditRecord : creditRecordList) {
            CreditRecordVO creditVO = new CreditRecordVO()
                    .setName(creditRecord.getName());

            if (creditRecord.getCredit() < 0) {
                creditVO.setValue(creditRecord.getCredit() + "积分");
            } else {
                creditVO.setValue("+" + creditRecord.getCredit() + "积分");
            }

            if (map.containsKey(creditRecord.getDate())) {
                map.get(creditRecord.getDate()).add(creditVO);
            } else {
                List<CreditRecordVO> list = new ArrayList<>();
                list.add(creditVO);
                map.put(creditRecord.getDate(), list);
            }
        }

        List<CreditDateVO> result = new ArrayList<>();
        for (Map.Entry<String, List<CreditRecordVO>> entry : map.entrySet()) {
            CreditDateVO creditDateVO = new CreditDateVO();
            creditDateVO.setDate(entry.getKey());
            creditDateVO.setCredit(entry.getValue());
            result.add(creditDateVO);
        }

        return result;
    }
}